﻿using PrinterMonitorSvc.Common;
using PrinterMonitorSvc.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrinterMonitorSvc.Ext
{
    /// <summary>
    /// 类型扩展方法
    /// </summary>
    public static class TypeExt
    {
        #region 将枚举类型转为List集合
        /// <summary>
        /// 将枚举类型转为List集合
        /// </summary>
        /// <param name="type">源类型</param>
        /// <returns>EnumBase类型集合</returns>
        public static List<EnumBase> ToList(this Type type)
        {
            if (!type.IsEnum) return null;
            List<EnumBase> list = new List<EnumBase>();
            foreach (int item in Enum.GetValues(type))
            {
                string name = Enum.GetName(type, item);//获取名称
                string value = item.ToString();//获取值
                string description = ((Enum)Enum.Parse(type, value)).ValueOfDescription();//获取描述
                list.Add(new EnumBase()
                {
                    Name = name,
                    Value = value,
                    Description = description
                });
            }
            return list;
        }
        #endregion

        #region 安全返回值
        /// <summary>
        /// 安全返回值
        /// </summary>
        /// <param name="value">可空值</param>
        public static TEntity SafeValue<TEntity>(this TEntity? value) where TEntity : struct
        {
            return value ?? default(TEntity);
        }
        #endregion

        #region 将实体对象转换成json字符串
        /// <summary>
        /// 将实体对象转换成json字符串
        /// </summary>
        /// <param name="type">对象</param>
        /// <returns>json字符串</returns>
        public static string ToJson<TEntity>(this TEntity type) where TEntity : class
        {
            return JsonHelper.ConvertJson(type);
        }
        #endregion
    }
}
